package com.example.myapplication;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class CardGameActivity extends AppCompatActivity {

    private CardGameModel gameModel;
    private CardAdapter cardAdapter;
    private GridView gridViewCards;
    private TextView tvScore;
    private Button btnRestart, btnBack;
    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_card_game);
        
        initViews();
        initGame();
        setupClickListeners();
    }

    private void initViews() {
        gridViewCards = findViewById(R.id.gridViewCards);
        tvScore = findViewById(R.id.tvScore);
        btnRestart = findViewById(R.id.btnRestart);
        btnBack = findViewById(R.id.btnBack);
        handler = new Handler();
    }

    private void initGame() {
        gameModel = new CardGameModel();
        cardAdapter = new CardAdapter(gameModel.getCards(), getLayoutInflater());
        gridViewCards.setAdapter(cardAdapter);
        updateScore();
        
        gridViewCards.setOnItemClickListener((parent, view, position, id) -> {
            if (gameModel.isChecking() || gameModel.isGameOver()) {
                return;
            }
            
            gameModel.flipCard(position);
            cardAdapter.notifyDataSetChanged();
            updateScore();
            
            if (gameModel.isChecking()) {
                // 延迟检查匹配结果
                handler.postDelayed(() -> {
                    if (!gameModel.getFirstSelectedCard().isMatched()) {
                        // 匹配失败，翻转回去
                        gameModel.flipBackUnmatchedCards();
                        cardAdapter.notifyDataSetChanged();
                    } else {
                        // 匹配成功，继续游戏
                        gameModel.resetSelection();
                    }
                    
                    // 检查游戏是否结束
                    if (gameModel.isGameOver()) {
                        showGameOverMessage();
                    }
                }, 1000);
            }
        });
    }

    private void updateScore() {
        tvScore.setText(getString(R.string.score) + ": " + gameModel.getScore());
    }

    private void setupClickListeners() {
        btnRestart.setOnClickListener(v -> {
            gameModel.initializeGame();
            cardAdapter.updateCards(gameModel.getCards());
            updateScore();
        });

        btnBack.setOnClickListener(v -> {
            Intent resultIntent = new Intent();
            resultIntent.putExtra("score", gameModel.getScore());
            setResult(RESULT_OK, resultIntent);
            finish();
        });
    }

    private void showGameOverMessage() {
        String message = getString(R.string.game_over) + " " + 
                        getString(R.string.final_score, gameModel.getScore());
        Toast.makeText(this, message, Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
    }
}